<template>
    <el-card class="box-card" shadow="never">
        <div ref="chartRef" id="chartRate" class="chart-container"></div>
    </el-card>
</template>
<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted } from 'vue'
import $axios from '../../../utils/axios'

const tableData = ref([])
const chartRef = ref(null)
let chart = null

// 定义初始化echarts图表的方法
const initChart = (chartData) => {
    if (!chartRef.value) {
        console.error('找不到图表容器')
        return
    }

    // 如果已经有图表实例，先销毁它
    if (chart) {
        chart.dispose()
        chart = null
    }

    try {
        // 初始化图表
        chart = echarts.init(chartRef.value)

        // 配置图表
        const options = {
            title: {
                text: '活动报名率统计',
                left: 'center',
                top: 20
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                top: '15%',
                bottom: '15%',
                left: '10%',
                right: '10%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: chartData.map(item => item.activityName),
                axisLabel: {
                    rotate: -30,
                    interval: 0,
                    formatter: function (value) {
                        return value.length > 12 ? value.substring(0, 12) + '...' : value
                    }
                }
            },
            yAxis: {
                type: 'value',
                name: '报名率',
                nameTextStyle: {
                    padding: [0, 0, 0, 40]
                },
                axisLabel: {
                    formatter: '{value}%'
                }
            },
            series: [
                {
                    name: '报名率',
                    type: 'bar',
                    data: chartData.map(item => item.rate),
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#83bff6' },
                            { offset: 0.5, color: '#409EFF' },
                            { offset: 1, color: '#188df0' }
                        ])
                    },
                    emphasis: {
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#66b1ff' },
                                { offset: 0.7, color: '#409EFF' },
                                { offset: 1, color: '#0d84ff' }
                            ])
                        }
                    }
                }
            ]
        }

        // 设置图表配置项
        chart.setOption(options)

        // 添加窗口大小改变的监听
        window.addEventListener('resize', handleResize)
    } catch (error) {
        console.error('图表初始化失败:', error)
    }
}

// 处理窗口大小改变
const handleResize = () => {
    if (chart) {
        chart.resize()
    }
}

const init = async () => {
    try {
        // 获取统计数据
        const path = '/activity/findAll'
        const { data: res } = await $axios.get(path)
        if (res.code === 200 && res.result) {
            const chartData = res.result
                .filter(item => item.limitNum > 0) // 只统计有人数限制的活动
                .map(item => {
                    const signNum = parseInt(item.signNum) || 0
                    const limitNum = parseInt(item.limitNum) || 1
                    const rate = (signNum / limitNum * 100).toFixed(2)
                    return {
                        activityName: item.activityName || '未命名活动',
                        rate: parseFloat(rate)
                    }
                })
                .sort((a, b) => b.rate - a.rate) // 按报名率从高到低排序
                .slice(0, 5) // 只显示前5个活动

            console.log('活动报名率数据:', chartData)
            if (chartData.length > 0) {
                setTimeout(() => {
                    initChart(chartData)
                }, 100)
            } else {
                initChart([{
                    activityName: '暂无活动数据',
                    rate: 0
                }])
            }
        } else {
            console.warn('未获取到活动数据')
            initChart([{
                activityName: '暂无活动数据',
                rate: 0
            }])
        }
    } catch (error) {
        console.error('获取数据失败:', error)
        initChart([{
            activityName: '数据获取失败',
            rate: 0
        }])
    }
}

onMounted(() => {
    init()
})

onUnmounted(() => {
    // 移除窗口大小改变的监听
    window.removeEventListener('resize', handleResize)
    // 销毁图表实例
    if (chart) {
        chart.dispose()
        chart = null
    }
})

</script>

<style scoped>
.box-card {
    width: 100%;
    height: 100%;
    /* display: flex; */
    /* justify-content: center; */
    /* 水平居中 */
    /* text-align: center; */
    /* margin-top: 12px; */
    /* border-radius: 12px; */
}

.chart-container {
    width: 100%;
    height: 50vh;
    /* justify-content: center;
    align-items: center; */
    /* margin-left: 50%; */
}

/* .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
} */

/* .content {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    width: 100%;
} */
/* 
.el-table {
    width: 50%;
} */


.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}


#chart {
    margin-top: 12px;
    border-radius: 12px;
}
</style>

<style>
.el-table .success-row {
    --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>